using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;

namespace Admin.Net.Plugin.Api;

[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
internal class PlugRuleWraingBindService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<WarningRule> _rep;

	private readonly SqlSugarRepository<Room> _reproom;

	public PlugRuleWraingBindService(SqlSugarRepository<WarningRule> rep, SqlSugarRepository<Room> reproom)
	{
		_reproom = reproom;
		_rep = rep;
	}

	/// <summary>
	/// 获得绑定的房间
	/// </summary>
	/// <param name="id"></param>
	/// <returns></returns>
	[HttpGet("/plugwarningRule/getbindroom")]
	public async Task<dynamic> GetBindRoom(long id)
	{
		List<BindRoomOutput> list = new List<BindRoomOutput>();
		List<long> keyList = new List<long>();
		if (await (from u in _rep.Context.Queryable<Collector>()
			where u.Id == id
			select u).AnyAsync())
		{
			var meterInfo = await (from u in _reproom.AsQueryable()
				where u.WarningRuleId == null || u.WarningRuleId == (long?)id
				select u).LeftJoin((Room r, Building b) => r.BuildingId == b.Id).Select((Room u, Building b) => new
			{
				Id = u.Id,
				WarningRuleId = u.WarningRuleId,
				roomName = string.Concat(b.Name + "/", u.Name)
			}).ToListAsync();
			list = meterInfo.Select(u => new BindRoomOutput
			{
				Disabled = false,
				Key = u.Id,
				Label = u.roomName
			}).ToList();
			keyList = (from u in meterInfo
				where u.WarningRuleId == id
				select u.Id).ToList();
		}
		return new
		{
			LeftValue = list,
			rightValue = keyList
		};
	}

	/// <summary>
	/// 绑定
	/// </summary>
	/// <param name="meter"></param>
	/// <returns></returns>
	[HttpPost("/plugwarningRule/bindroom")]
	public async Task BindRoom(BindRoomInput room)
	{
		List<Room> result = await (from u in _reproom.AsQueryable()
			where u.WarningRuleId == (long?)room.RuleId || room.Id.Contains(u.Id)
			select u).ToListAsync();
		result.ForEach(delegate(Room u)
		{
			if (room.Id.Contains(u.Id))
			{
				u.WarningRuleId = room.RuleId;
			}
			else
			{
				u.WarningRuleId = null;
			}
		});
		_rep.Context.Updateable<ElectricMeter>(result).UpdateColumns((ElectricMeter u) => new { u.CollectorId }).ExecuteCommand();
	}
}
